﻿using System.Windows;
using System.Windows.Controls;

namespace Jerry.DroidBuilder.ThemeEditor.Controls
{
    public class NinePatchControl : ContentControl
    {
        /// <summary>
        /// Initializes a new instance of <see cref="NinePatchControl"/>.
        /// </summary>
        static NinePatchControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(NinePatchControl), new FrameworkPropertyMetadata(typeof(NinePatchControl)));
        }

        /// <summary>
        /// Gets or sets 9 patch display info.
        /// </summary>
        public DrawableInfo DisplayInfo
        {
            get { return (DrawableInfo)GetValue(DisplayInfoProperty); }
            set { SetValue(DisplayInfoProperty, value); }
        }

        /// <summary>
        /// Identifies the <see cref="DisplayInfo"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty DisplayInfoProperty =
            DependencyProperty.Register("DisplayInfo", typeof(DrawableInfo), typeof(NinePatchControl), new PropertyMetadata(null));

        public static DrawableInfo GetAttachedDisplayInfo(DependencyObject sender)
        {
            return (DrawableInfo)sender.GetValue(AttachedDisplayInfoProperty);
        }

        public static void SetAttachedDisplayInfo(DependencyObject sender, DrawableInfo value)
        {
            sender.SetValue(AttachedDisplayInfoProperty, value);
        }

        /// <summary>
        /// Identifies the <see cref="AttachedDisplayInfo"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty AttachedDisplayInfoProperty =
            DependencyProperty.RegisterAttached("AttachedDisplayInfo", typeof(DrawableInfo), typeof(NinePatchControl), new PropertyMetadata(null, OnAttachedDisplayInfoChanged));

        private static void OnAttachedDisplayInfoChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            var ctrl = sender as Grid;
            var info = GetAttachedDisplayInfo(ctrl);

            if (null != ctrl && null != info)
            {
                ctrl.RowDefinitions.Clear();

                foreach (var row in info.Rows)
                {
                    ctrl.RowDefinitions.Add(new RowDefinition { Height = row });
                }

                ctrl.ColumnDefinitions.Clear();

                foreach (var column in info.Columns)
                {
                    ctrl.ColumnDefinitions.Add(new ColumnDefinition { Width = column });
                }
            }
        }
    }
}
